#import "FileUtilities.h"

/**
 * FileUtilities is an object representing generic filesystem operations.
 *
 *
 * @author      Justin Hollander
 * @version     0.3.3
 * @since       0.3.3
 */
@implementation FileUtilities

/**
 * Retrieve write-permissible absolute path for storing this collection.
 *
 * Asks the iOS for the application's unique Documents directory.
 *
 * @param fileName  the name of the file in which to store this collection
 * @param subdir    the unique subdirectory holding all data for this collection
 * @return          the absolute path at which this collection is stored on succesfully
 *					creating the subdirectory. Nil is returned on failure.
 */
+ (NSString*)getPathWithFileName:(NSString*)fileName 
			   usingSubdirectory:(NSString*)subdir {
	NSFileManager* fileManager = [NSFileManager defaultManager];
	// Get the application's unique Documents directory
	NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
														 NSUserDomainMask, 
														 YES);
	// Get subdirectory path for storing this collection
	NSString* subdirectoryPath = [[paths objectAtIndex:0] 
								  stringByAppendingPathComponent:subdir];	
	// Create the directory if necessary
	if ([fileManager createDirectoryAtPath:subdirectoryPath 
			   withIntermediateDirectories:YES 
								attributes:nil 
									 error:nil])
		return [subdirectoryPath stringByAppendingPathComponent:fileName];
	else 
		return nil;
}

/**
 * Asks the iOS for the application's unique Documents directory and then attempts to
 * create a subdirectory within it.
 *
 * @param subdirectory    the unique subdirectory holding all data for this collection
 * @return                YES on success;
 *                        NO otherwise.
 */
+ (BOOL)createSubDirectory:(NSString*)subdirectory {
	NSFileManager* fileManager = [NSFileManager defaultManager];
	// Get the application's unique Documents directory
	NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
														 NSUserDomainMask, 
														 YES);
	// Get subdirectory path for storing this collection
	NSString* subdirectoryPath = [[paths objectAtIndex:0] 
								  stringByAppendingPathComponent:subdirectory];	
	// Create the directory if necessary
	return [fileManager createDirectoryAtPath:subdirectoryPath 
				  withIntermediateDirectories:YES 
								   attributes:nil 
										error:nil];
}

/**
 * Get the path for a file from the resource bundle for the application.
 *
 * @param fileName  the file name of the resource
 * @return          the absolute path to the resource file
 */
+ (NSString*)getResource:(NSString*)fileName {
	NSArray* file = [fileName componentsSeparatedByString:@"."];
	return [[NSBundle mainBundle] pathForResource:[file objectAtIndex:0] 
										   ofType:[file objectAtIndex:1]];
}

@end
